package com.dapeis.web.wx.wx.handler;

import java.util.Map;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import com.ag.module.common.web.TagUtils;
import com.dapeis.domain.UserThirdPartyLogin;
import com.dapeis.service.UserService;
import com.dapeis.service.UserThirdPartyLoginService;

/**
 * 
 * Title:WxEventCustomCmdHandler.java WxEventCustomCmdHandler Description:
 * 
 * @author yuanyong
 * @date 2017年4月18日 上午9:20:11 Email: hzyuanyong@126.com
 *
 */
@Component
public class WxEventCustomCmdHandler implements WxMpMessageHandler {

    private Pattern gzsjPattern = Pattern.compile("(?i:gzsj)|关注时间");

    @Resource
    UserService userService;
    @Resource
    UserThirdPartyLoginService userThirdPartyLoginService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
	    Map<String, Object> context, WxMpService wxMpService,
	    WxSessionManager sessionManager) throws WxErrorException {

	String content = wxMessage.getContent();
	if (StringUtils.isNotBlank(content)
		&& gzsjPattern.matcher(content).matches()) {

	    UserThirdPartyLogin userThirdPartyLogin = userThirdPartyLoginService
		    .getWxUserThirdPartyLogin(wxMessage.getFromUserName());
	    WxMpCustomMessage gzsj = WxMpCustomMessage
		    .TEXT()
		    .toUser(wxMessage.getFromUserName())
		    .content(
			    "时间: "
				    + TagUtils.formatDate(userThirdPartyLogin
					    .getRecordCreateTime(),
					    "MM-dd HH:mm")).build();
	    try {
		wxMpService.customMessageSend(gzsj);
	    } catch (WxErrorException e) {
		e.printStackTrace();
	    }
	}
	return null;
    }
}
